<template>
  <div class="page-wrapper">
    <c-card title="工单列表" class="user-list">
      <!-- <el-button slot="func" size="small" @click="showAddDlg(null)">创建工单</el-button> -->
      <div class="search-row">
        <div>
          <div class="item">
            <label>开始日期</label>
            <el-date-picker
              v-model="startDate"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="请选择开始日期"
              size="small"
            ></el-date-picker>
          </div>
          <div class="item">
            <label>结束日期</label>
            <el-date-picker
              v-model="endDate"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="请选择结束日期"
              size="small"
            ></el-date-picker>
          </div>
          <div class="item">
            <label>负责人</label>
            <!-- <el-select v-model="fzer" size="small" placeholder="请选择">
                <el-option v-for="u in users" :key="u.pkid" :label="u.name" :value="u.pkid"></el-option>
            </el-select>-->
            <el-input v-model="fzer" size="small"></el-input>
          </div>
          <div class="item">
            <label>客户</label>
            <el-input v-model="client" size="small"></el-input>
          </div>
          <!-- 新增状态查询 -->
          <div class="item">
            <label>状态</label>
            <el-select v-model="statusId" placeholder="请选择状态">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <!-- 新增状态查询 end  -->
          <el-button size="small" type="primary" class="item" @click="_getWorkorders">查询</el-button>
        </div>
      </div>
      <el-table ref="table" v-loading="loading" :data="historyData" stripe style="width: 100%">
        <el-table-column prop="name" label="工单名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="processName" label="流程名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="priorityId" label="优先级">
          <template v-slot="{row}">
            <div>{{ row.priorityId && priorityList[4 - row.priorityId] }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="begin" label="开始时间" show-overflow-tooltip></el-table-column>
        <el-table-column prop="days" label="期限(天)"></el-table-column>
        <el-table-column prop="chargePersonName" label="负责人" show-overflow-tooltip></el-table-column>
        <el-table-column prop="clientName" label="客户" show-overflow-tooltip></el-table-column>
        <el-table-column prop="substationname" label="变电箱/站" show-overflow-tooltip></el-table-column>
        <el-table-column label="状态">
          <template v-slot="{ row }">{{ statusName[row.statusId] }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row, $index}">
            <el-button
              v-if="row.statusId === 0"
              size="small"
              type="text"
              @click="showEditDlg(row, $index)"
            >修改</el-button>
            <el-button
              v-if="row.statusId === 0"
              size="small"
              type="text"
              @click="publish(row, $index)"
            >发布</el-button>
            <el-button size="small" type="text" @click="showDetailDlg(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :page-size="page.size"
          :current-page.sync="page.index"
          :total="page.total"
          @current-change="_getWorkorders"
        ></el-pagination>
      </div>
    </c-card>
    <c-dlg
      :title="workorder.pkid ? '工单编辑' : '工单创建'"
      :visible.sync="dialogVisible"
      @close="$store.commit('alarm/SHOW')"
    >
      <el-form
        ref="form"
        :model="workorder"
        :rules="rules"
        label-width="60px"
        class="demo-ruleForm"
        label-position="top"
      >
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="工单名称" prop="name">
              <el-input v-model="workorder.name" size="small"></el-input>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="流程名称" prop="processDefId">
              <el-select v-model="workorder.processDefId" size="small" @change="getFlowCode">
                <el-option
                  v-for="p in processes"
                  :key="p.pkid"
                  :label="p.processName"
                  :value="p.pkid"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="优先级别" prop="priorityId">
              <el-select v-model="workorder.priorityId" size="small">
                <el-option v-for="(p, i) in priorityList" :key="i" :value="4-i" :label="p"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="期限(天)" prop="days">
              <el-input v-model="workorder.days" size="small" @change="limitDayChange"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="开始日期" prop="begin">
              <el-date-picker
                v-model="workorder.begin"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择开始日期"
                size="small"
                @change="startChange"
              ></el-date-picker>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="结束日期" prop="end">
              <el-date-picker
                v-model="workorder.end"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择结束日期"
                size="small"
                @change="endChange"
              ></el-date-picker>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="负责人" prop="chargePersonId">
              <el-select v-model="workorder.chargePersonId" size="small" placeholder="请选择">
                <el-option v-for="u in users" :key="u.pkid" :label="u.name" :value="u.pkid"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="抄送人" prop="copierId">
              <el-select v-model.number="workorder.copierId" size="small" placeholder="请选择">
                <el-option v-for="u in users" :key="u.pkid" :label="u.name" :value="u.pkid"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="客户" prop="clientId">
              <el-select
                v-model="workorder.clientId"
                filterable
                size="small"
                @change="clientChange"
              >
                <el-option v-for="c in comList" :key="c.pkid" :label="c.name" :value="c.pkid"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <span class="spliter"></span>
          <div class="row-item">
            <el-form-item label="变电箱/站" prop="stationIds">
              <el-select v-model="workorder.stationIds" size="small" multiple placeholder="请选择">
                <el-option v-for="u in stations" :key="u.pkid" :label="u.name" :value="u.pkid + ''"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <el-form-item label="工单描述" prop="details" style="width: 100%">
            <el-input v-model="workorder.details" type="textarea" size="small"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="submitForm">提交</el-button>
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
      </div>
    </c-dlg>
    <c-dlg :visible.sync="detailVisible" title="详情" :type="2">
      <work-detail :id="curId"></work-detail>
    </c-dlg>
  </div>
</template>

<script>
import CCard from "@/components/CCard";
import CDlg from "@/components/CDlg";
import WorkDetail from "./components/Detail";
import { calcDate, diffDate, parseTime, calcPageNum } from "@/utils";
import { clone } from "lodash";
// import { deepClone } from '../../utils';
export default {
  components: {
    CCard,
    CDlg,
    WorkDetail
  },
  data() {
    return {
      startDate: null,
      endDate: null,
      fzer: null,
      client: null,
      statusName: ["未发布", "启动", "完成", "进行过程"],
      loading: false,
      newWorkorder: {},
      processes: null,
      users: null,
      // clients: null,
      stations: null,
      searchText: "",
      workorderList: [],
      dialogVisible: false,
      workorder: {},
      page: {
        index: 1,
        size: 10,
        total: 0
      },
      rules: {
        name: [{ required: true, message: "该字段不能为空", trigger: "blur" }],
        processDefId: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        priorityId: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        days: [{ required: true, message: "该字段不能为空", trigger: "blur" }],
        begin: [{ required: true, message: "该字段不能为空", trigger: "blur" }],
        end: [{ required: true, message: "该字段不能为空", trigger: "blur" }],
        chargePersonId: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        clientId: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        stationIds: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        // details: [
        //   { required: true, message: "该字段不能为空", trigger: "blur" }
        // ]
      },
      priorityList: ["高", "中", "低", "一般"],
      detailVisible: false,
      curId: null,
      statusId: '2',
      options: [
        // {
        //   value: '0',
        //   label: '未发布'
        // },
        // {
        //   value: '1',
        //   label: '启动'
        // },
        {
          value: '2',
          label: '结束'
        },
        // {
        //   value: '3',
        //   label: '进行过程'
        // }
      ],
      // 过滤后的数据 =》完成
      historyData: []
    };
  },
  computed: {
    newOrder() {
      return this.$store.getters.newOrder;
    },
    comList() {
      return this.$store.getters.comList;
    }
  },
  watch: {
    "page.index"(v) {
      const path = this.$route.path;
      this.$router.push(path + "?page=" + v);
    },
    newOrder: {
      handler(o) {
        if (!o) {
          return;
        }
        if (o.clientId) {
          this.getStations(o.clientId).then(() => {
            this.showAddDlg(o);
          });
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    const page = this.$route.query.page || 1;
    this.$set(this.page, "index", parseInt(page));
  },
  mounted() {
    const h = this.$refs["table"].$el.clientHeight;
    const n = calcPageNum(h);
    this.$set(this.page, "size", n);
    // this._getWorkorders();
    this.getUsers();
    this.OtherDade();
  },
  methods: {
    // 确定查询 发布
    _getWorkorders() {
      this.ajaxData()
    },
    OtherDade() {
      this.ajaxData()
    },
    ajaxData() {
      const params = {
        page: this.page.index,
        rows: this.page.size,
        start: this.startDate,
        end: this.endDate,
        chargePersonName: this.fzer || undefined,
        client: this.client || undefined,
        statusId: this.statusId
      };
      this.loading = true;
      // todo get workorder api
      return this.$axios
        .get("plat/work/baseInfo", { params })
        .then(res => {
          if (res.code === 1) {
            const historyData = res.data.rows;
            historyData.map(d => {
              d.stationIds = d.stationId.split(",");
              return d;
            });
            // 只渲染完成得
            // this.historyData = historyData.filter(item => item.statusId === 2)
            this.historyData = historyData
            this.$set(this.page, "total", res.data.total);
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e))
        .finally(() => {
          this.loading = false;
        });
    },
    getProcess() {
      if (this.processes) return;
      const params = {
        processName: this.processName,
        rows: 100,
        page: 1
      };

      return this.$axios
        .get("plat/work/queryProcess", { params })
        .then(res => {
          if (res.code === 1) {
            this.processes = res.data.rows;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    getUsers() {
      if (this.users) return;
      return this.$axios
        .get("/plat/work/drop/sys_user")
        .then(res => {
          if (res.code === 1) {
            this.users = res.data;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    // getClients(name) {
    //   const params = {
    //     name: name || "",
    //     page: 1,
    //     rows: 20
    //   };
    //   return this.$axios
    //     .get("plat/user/queryClient", { params })
    //     .then(res => {
    //       if (res.code === 1) {
    //         this.clients = res.data.rows;
    //       } else {
    //         throw res.msg;
    //       }
    //     })
    //     .catch(e => this.$message.error(e));
    // },
    getStations(id) {
      const params = {
        // name: name || "",
        // page: 1,
        // rows: 20
        pkid: id
      };
      return this.$axios
        .get("plat/work/dropSubstation", { params })
        .then(res => {
          if (res.code === 1) {
            this.stations = res.data;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    publish(row, index) {
      const r = clone(row);
      r.statusId = 1;
      return this.$axios
        .post("plat/work/edit", r)
        .then(res => {
          if (res.code === 1) {
            this.historyData.splice(index, 1, res.data);
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    async showAddDlg(o = null) {
      if (o) {
        this.workorder = clone(o);
      } else if (this.workorder.pkid) {
        this.workorder = {};
      }
      this.getUsers();
      this.getProcess();
      // this.getClients();
      this.getStations(this.workorder.clientId);
      this.dialogVisible = true;
    },
    showEditDlg(wo, index) {
      this.flowCode = null;
      this.getUsers();
      this.getProcess();
      // this.getClients();
      this.getStations(wo.clientId);
      if (this.workorder.pkid !== wo.pkid) {
        this.workorder = clone(wo);
        this.curWorkorderId = wo.pkid;
      }
      this.curIndex = index;
      this.dialogVisible = true;
    },
    changeStatus(wo) {
      if (!wo.status) {
        this.$set(wo, "status", 1);
      } else {
        this.$set(wo, "status", 0);
      }
    },
    getFlowCode(id) {
      const a = this.processes.filter(e => e.pkid === id)[0];
      this.flowCode = a && a.processCode;
    },
    // 创建工单
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.workorder.flowCode = this.flowCode || this.workorder.flowCode;
          this.workorder.stationId = this.workorder.stationIds.join(",");
          this.$axios
            .post("plat/work/edit", this.workorder)
            .then(res => {
              if (res.code === 1) {
                this._getWorkorders();
                this.workorder = {};
                this.dialogVisible = false;
              } else {
                throw res.msg;
              }
            })
            .catch(e => this.$message.error(e));
        }
      });
    },
    limitDayChange(days) {
      if (!days || +days < 0) return;
      if (this.workorder.begin) {
        const e = parseTime(
          calcDate(this.workorder.begin, days),
          "{y}-{m}-{d}"
        );
        this.$set(this.workorder, "end", e);
      } else if (this.workorder.end) {
        const s = parseTime(calcDate(this.workorder.end, -days), "{y}-{m}-{d}");
        this.$set(this.workorder, "begin", s);
      }
    },
    startChange(begin) {
      if (!begin) return;
      if (this.workorder.days) {
        const e = parseTime(
          calcDate(begin, this.workorder.days),
          "{y}-{m}-{d}"
        );
        this.$set(this.workorder, "end", e);
      } else if (this.workorder.end) {
        const d = diffDate(begin, this.workorder.end);
        this.$set(this.workorder, "days", d);
      }
    },
    endChange(end) {
      if (!end) return;
      if (this.workorder.begin) {
        const d = diffDate(this.workorder.begin, end);
        if (d <= 0) {
          this.$set(this.workorder, "end", null);
          return false;
        }
        this.$set(this.workorder, "days", d);
      } else if (this.workorder.days) {
        const s = parseTime(calcDate(end, this.workorder.days), "{y}-{m}-{d}");
        this.$set(this.workorder, "begin", s);
      }
    },
    clientChange(id) {
      this.stations = null;
      this.$set(this.workorder, "stationId", null);
      this.getStations(id);
    },
    showDetailDlg(row) {
      this.curId = row.pkid;
      this.detailVisible = true;
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
